<template>
  <div class="info-container">
    <el-card>
      <el-breadcrumb separator="/">
        <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
        <el-breadcrumb-item>详情</el-breadcrumb-item>
      </el-breadcrumb>
      <el-form label-width="200px">
        <el-form-item label="课程名称：">{{ info.name || '' }}</el-form-item>
        <el-form-item label="课程分类：">{{ typesMap[info.typeName] || info.typeName }}</el-form-item>
        <el-form-item label="课程教师：">{{ teacherMap[info.thSno] || info.thSno }}</el-form-item>
        <el-form-item label="价格：">
          <span class="text-red2">￥{{ info.price || 0 }}</span>
        </el-form-item>
        <el-form-item label="预约时间：">


          <el-date-picker
              v-model="formData.times"
              value-format="YYYY-MM-DD HH:mm:ss"
              type="daterange"
              :disabled-date="(time) => {
                // 禁止预约昨天以前的时间
                // 参考 https://element-plus.gitee.io/zh-CN/component/date-picker.html#disabledDate
                return time.getTime() < (Date.now() - 86400000);
              }"
              start-placeholder="Start"
              end-placeholder="End">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="">
          <el-button @click="onCreateOrder" type="success">
            立即预约
          </el-button>
        </el-form-item>
      </el-form>

    </el-card>

    <el-card class="m_y10" v-if="info.remarks&&info.remarks.length&&info.coverImg&&info.coverImg.length">
      <div class="p_y20">{{ info.remarks }}</div>

      <div class="row-align-center flex-wrap images">
        <el-image class="image" alt="" :src="info.coverImg"></el-image>
      </div>
    </el-card>

  </div>
</template>

<script>
import {computed, defineComponent, reactive, ref} from "vue"
import {useRoute, useRouter} from "vue-router";
import Course from "../api/modules/Course";
import {bcAdd, bcMul} from "../utils/helpers";
import Toast from "../utils/Toast";
import Orders from "../api/modules/Orders";
import {useStore} from "vuex";
import {RoleTypes, useUserLogin} from "../hooks/user/useUserLogin";
import Events from "../events/Events";
import {useCourseTypes} from "../hooks/useCourseTypes";
import {useTeachers} from "../hooks/useTeachers";

export default defineComponent({
  name: "GoodInfo",
  setup() {
    const store = useStore();
    const router = useRouter();
    const route = useRoute();
    const loginHandle = useUserLogin();
    const typesHandle = useCourseTypes();
    const teacherHandle = useTeachers();
    const info = ref({})
    const formData = reactive({
      serverIds: [],
      times: [],
      days: "",
    })
    getInfo(route.query.id)


    async function getInfo(goodId) {
      try {
        const {data} = await Course.info(goodId);
        if (data) {
          try {
            data.images = JSON.parse(data.images)
          } catch (e) {
            data.images = [];
          }
          info.value = data;
        }
        console.log(data)
      } catch (e) {

      }
    }

    async function onCreateOrder() {
      const userInfo = store.state.user.userInfo;
      const role = store.state.user.role;
      if (!userInfo.id || role !== RoleTypes.student) { // 未登录学生账号
        Toast.info("请先登录学生账号后进行预约")
        setTimeout(() => {
          loginHandle.removeUserInfo(false); // 当管理员、教师登录时自动退出（仅学生用户登录可购买）
          window.emitter.emit(Events.showLoginModal, RoleTypes.student); // 触发显示登录弹框事件
        }, 800)
        return;
      }
      const {times} = formData;
      if (times.length !== 2) {
        Toast.warning('请指定预约时间');
        return;
      }
      try {

        let teacher = {};
        for (let t of teacherHandle.teacherData.value) {
          if (t.id == info.value.thSno) {
            teacher = t;
            break;
          }
        }
        const {message} = await Orders.create({
          startTime: times[0],
          endTime: times[1],
          courseId: info.value.id,
          price: info.value.price,
          userId: userInfo.id,
          userName: userInfo.name,
          thId: teacher.id,
          thName: teacher.name,
        });
        Toast.success(message);
        window.emitter.emit(Events.refreshUserInfo, RoleTypes.student); // 刷新用户信息
        router.push('/'); // 返回首页
      } catch (e) {
        Toast.warning(e.message);
      }
    }

    return {
      ...typesHandle,
      ...teacherHandle,
      info,
      formData,
      onCreateOrder,
    }
  },
})
</script>

<style lang="scss" scoped>
.info-container {
  .left-box {
    width: 400px;
  }

  .images {
    .image {
      max-width: 100%;
    }
  }
}

</style>
